window.onload = function () {
    var btn = document.getElementById("all");
    btn.onclick = function () {
        var flag = this.checked;
        var items = document.getElementsByName("sub");
        for (var i = 0; i < items.length; i++) {
            items[i].checked = flag;//将所有item的状态设为全选按钮的状态
        }
    }

    var items = document.getElementsByName("sub");
    for (var i = 0; i < items.length; i++) {
        items[i].onclick = function () {//对每个item设置点击
            var number = 0;//记录选中的个数
            for (var j = 0; j < items.length; j++) {
                if (items[j].checked) {
                    number++;
                }
            }
            document.getElementById("all").checked = (items.length == number);
        }
    }
    $("#totalmon").html(parseInt("00.00"));
}

var userid = getCookie("userid")


$.ajax({
    url: "http://localhost:8080/cart/cartall",
    type: "get",
    data: "userid=" + userid,
    //data: "userid=4",
    dataType: "json",
    success: function (data) {
        if (data.code == 1) {
            $("#empty").remove()
            $("#mainArea").attr("style", "display:block;")
        }
        //alert(data.code)
        let html = ''
        var totalmon = data.data[0].cartTotalMoney
        $("#totalmon").html(totalmon);
        $.each(data.data, function (index, value) {
            html += `<tr>
             <td class="umino-product-remove" style="vertical-align: middle">
                <input type="checkbox" name="sub" value="${value.cartGoodId}" onchange="getChecked()">&nbsp;&nbsp;
             
                <button type="button" name="del" value="${value.cartId}" data-id="${value.cartId}" data-toggle="modal" data-target="#myModal">
                <i class="fa fa-trash" title="Remove" ></i>
                </button>
             </td>
             
             <td class="umino-product-thumbnail" style="width:450px ">
                <div style="float: left;width: 120px">
                    <img  src="${value.goodPhoto}" >
                </div>
                <div style="max-width: 260px;overflow: hidden;white-space: nowrap;
                text-overflow: ellipsis;table-layout: fixed;margin-left: 160px;text-align: center">
                <a style="line-height: 130px">${value.goodName}</a>
                </div>
             </td>
             
             <td style="vertical-align: middle;" class="quantity">
               <div class="cart-plus-minus"  style="text-align: center">
                   <input class="cart-plus-minus-box" name="num" 
                     value="${value.cartGoodSize}" type="number" disabled >
               </div>
             </td>
             
             <td style="vertical-align: middle" class="umino-product-price">
             ${value.goodMoney}
             </td>
             
             <td style="vertical-align: middle" class="quantity">                      
               <div class="cart-plus-minus" style="text-align: center">
                   <input class="cart-plus-minus-box" name="num" 
                     value="${value.cartGoodNum}" type="number" oninput="updateNum(this)" >
               </div>
             </td>
                                    
             <td style="vertical-align: middle" class="product-subtotal" name="subMon">${value.cartGoodSubmon}</td>
             </tr>`
        })
        $("table").append(html)
    }
})


//数量框失焦事件
function updateNum(obj) {
    var num = $(obj).val()
    var price = parseInt($(obj).parent().parent().prev().html())
    var subPrice = num * price
    $(obj).parent().parent().next().html(subPrice)
    var toMon = 0
    $("td[name='subMon']").each(function (j, item) {
        toMon += parseInt(item.innerText)
    });
    getChecked()

}

var cartId;

// 触发模态框的按钮
$('#myModal').on('show.bs.modal', function (event) {

    var button = $(event.relatedTarget) // Button that triggered the modal
    // 从data-*内容中获取数据
    cartId = button.data('id') // Extract info from data-* attributes
    // 获取到modal 模态框对象
    var modal = $(this)
    modal.find('.modal-title').text('购物车删除')

})

//模态框
$("#myModal .modal-footer button").eq(1).click(function () {
    $.getJSON("http://localhost:8080/cart/delOneCart?cartId=" + cartId, data => {
        if (data == 1) {
            location.reload();
        } else {
            alert("删除失败")
        }
    })
    $('#myModal').modal('toggle')
})


var ids
var delids
var submon = 0

function fre() {
    ids = $("input:checkbox[name='sub']:checked").map(function (index, elem) {
        return $(elem).val() + "," + $(elem).parent().next().next().children().children().val() + "," + $(elem).parent().next().next().next().next().children().children().val();
    }).get().join(';');

    delids = $("input:checkbox[name='sub']:checked").map(function (index, elem) {
        return $(elem).next().val()
    }).get().join(',');

}

function getChecked() {
    submon = 0
    $("input:checkbox[name='sub']:checked").map(function (index, elem) {
        submon += parseInt($(elem).parent().next().next().next().next().next().html())
    });
    //alert(submon)
    $("#totalmon").html(parseInt(submon));
}


//结账按钮事件
function submitAll() {
    fre()
    //console.log(ids)

    if (ids.length == 0) {
        alert("还未选中商品！")
    } else {
        //delChos()
        url = "http://localhost:63343/qiguai/html/order.html?ids=" + ids;//此处拼接内容
        window.location.href = url;
    }
}


function delChos() {
    fre()
    //alert(delids)
    $.ajax({
        url: "http://localhost:8080/cart/delCarts",
        type: "get",
        data: "ids=" + delids,
        dataType: "json",
        success: function (data) {
            if (data.data > 0) {
                alert("移出购物车成功")
                location.reload();
            } else {
                alert("移出购物车失败")
            }
        }
    })
}

function subscribeBtn() {
    alert("订阅成功！")
}